from django.shortcuts import render

# 导入Response包
from rest_framework.response import Response

# 导入APIView包
from rest_framework.views import APIView

# 解析jwt_token的模块
from rest_framework_jwt.utils import jwt_decode_handler

# 导入随机包
import random

import time

# 导入序列化器
from miaoapp.miaoser import *


# 获取货物类型信息
class FixInfo(APIView):
    def get(self, request):
        # 当前页面
        page = request.GET.get('page', None)
        # 一页有多少条商品
        size = request.GET.get('size', None)
        # 定义从哪开始切片
        data_start = (int(page) - 1) * int(size)
        # 定义切到哪
        data_end = int(page) * int(size)
        # 获取全部标签信息
        fix = Fixing.objects.filter(is_delete=0)[data_start:data_end]
        total = Fixing.objects.filter(is_delete=0).count()
        fixinfo = FixingSer(fix, many=True).data
        return Response({'code': 200, 'fixinfo': fixinfo, 'total': total})


# 获取标签信息
class TagInfo(APIView):
    def get(self, request):
        # 获取需要获取的用户类型
        active_name = request.GET.get('activeName', None)
        if not active_name:
            tag = Tag.objects.filter(status=0)
            taginfo = TagSer(tag, many=True).data
            return Response({'code': 200, 'taginfo': taginfo})
        # 当前页面
        page = request.GET.get('page', None)
        # 一页有多少条商品
        size = request.GET.get('size', None)
        # 定义从哪开始切片
        data_start = (int(page) - 1) * int(size)
        # 定义切到哪
        data_end = int(page) * int(size)

        # 获取全部标签信息
        if active_name == '全部':
            tag = Tag.objects.all()[data_start:data_end]
            total = Tag.objects.all().count()
            taginfo = TagSer(tag, many=True).data
            return Response({'code': 200, 'taginfo': taginfo, 'total': total})
        # 获取待审核的用户
        elif active_name == '使用中':
            tag = Tag.objects.filter(is_delete=0)[data_start:data_end]
            total = Tag.objects.filter(is_delete=0).count()
            taginfo = TagSer(tag, many=True).data
            return Response({'code': 200, 'taginfo': taginfo, 'total': total})
        # 获取审核通过的用户(只返回未归档的用户)
        elif active_name == '存档':
            tag = Tag.objects.filter(is_delete=1)[data_start:data_end]
            total = Tag.objects.filter(is_delete=1).count()
            taginfo = TagSer(tag, many=True).data
            return Response({'code': 200, 'taginfo': taginfo, 'total': total})


# 添加标签
class AddTag(APIView):
    def post(self, request):
        # 获取用户token
        token = request.data.get('token', None)
        # 解析出用户信息
        user = jwt_decode_handler(token)
        uid = user.get('user_id')
        # 获取数据
        addtag = request.data.get('AddTag', None)
        # 将数据存储到数据库
        Tag.objects.create(tag_id=addtag['tagid'], fen_uid=addtag['username'], fix_id=addtag['fixing'], create_uid=uid)
        return Response({'code': 200, 'message': '添加成功'})

    def put(self, request):
        # 获取数据
        data = request.data.get('UpdateTag', None)
        # 查询该标签
        tag = Tag.objects.get(id=int(data['id']))
        # 更新标签信息
        tag.fix_id = data['fix_id']
        tag.fen_uid = data['fen_uid']
        tag.update_time = datetime.now()
        # 保存
        tag.save()
        return Response({'code': 200, 'message': '修改成功'})

    def delete(self, request):
        # 获取归档的标签id
        tid = request.GET.get('tid', None)
        # 查询标签
        tag = Tag.objects.get(id=int(tid))
        # 逻辑删除此标签
        tag.is_delete = 1
        # 保存
        tag.save()
        return Response({'code': 200, 'message': '归档成功'})


# 获取货物类型
class FixingInfo(APIView):
    def get(self, request):
        fixing = Fixing.objects.all()
        fixinfo = FixingSer(fixing, many=True).data
        return Response({'code': 200, 'fixinfo': fixinfo})


# 添加货物类型
class AddFixing(APIView):
    def post(self, request):
        # 获取货物类型
        fixing = request.data.get('Fixing', None)
        # 获取报警类型
        baojing = request.data.get('BaoJing', None)

        # 查询设备名称，在添加货物类型时，将名称替换成id
        genre = Genre.objects.filter(name=fixing['genre']).first()
        # 判断获取到的温度大小---将温度低的赋值给Min_WenDu，将温度高的赋值给Max_WenDu
        if fixing['Min_WenDu'] < fixing['Max_WenDu']:
            Min_WenDu, Max_WenDu = fixing['Min_WenDu'], fixing['Max_WenDu']
        else:
            Min_WenDu, Max_WenDu = fixing['Max_WenDu'], fixing['Min_WenDu']
        # 将货物类型添加到数据库中
        fix = Fixing.objects.create(
            genre_id=genre.id, name=fixing['name'], desc=fixing['desc'], delay_time=fixing['delay_time'],
            ent_time=fixing['ent_time'], min_temp=Min_WenDu, max_temp=Max_WenDu
        )
        # 遍历设置的报警类型
        for bj in baojing:
            # 判断阈值的单位
            if bj['YuZhiDanWei'] == '分':
                if type(bj['YuZhiValue']) == int:
                    # 将分钟转换成秒
                    bj['YuZhiValue'] = int(bj['YuZhiValue']) * 60
                else:
                    # 将分钟转换成秒
                    bj['YuZhiValue'] = int(float(bj['YuZhiValue']) * 60)
            elif bj['YuZhiDanWei'] == '小时':
                if type(bj['YuZhiValue']) == int:
                    # 将小时转换成秒
                    bj['YuZhiValue'] = int(bj['YuZhiValue']) * 60 * 60
                else:
                    bj['YuZhiValue'] = int(float(bj['YuZhiValue']) * 60 * 60)
            else:
                # 将天转换成秒
                if type(bj['YuZhiValue']) == int:
                    bj['YuZhiValue'] = int(bj['YuZhiValue']) * 60 * 60 * 24
                else:
                    bj['YuZhiValue'] = int(float(bj['YuZhiValue']) * 60 * 60 * 24)

            # 如果报警设置有上限及下限温度
            if bj['Min_WenDu'] and bj['Max_WenDu']:
                # 判断获取到的温度大小---将温度低的赋值给Min_WenDu，将温度高的赋值给Max_WenDu
                if bj['Min_WenDu'] < bj['Max_WenDu']:
                    bj['Min_WenDu'], bj['Max_WenDu'] = bj['Min_WenDu'], bj['Max_WenDu']
                else:
                    bj['Min_WenDu'], bj['Max_WenDu'] = bj['Max_WenDu'], bj['Min_WenDu']
            # 如果最低温度不存在
            if not bj['Min_WenDu']:
                bj['Min_WenDu'] = ''
            # 如果最高温度不存在
            if not bj['Max_WenDu']:
                bj['Max_WenDu'] = ''
            # 将报警信息添加到数据库中
            Warn.objects.create(
                name=bj['BaoJingTypeValue'], fix_id=fix.id, min_temp=bj['Min_WenDu'], max_temp=bj['Max_WenDu'],
                doorsill=bj['YuZhiValue']
            )
        return Response({'code': 200, 'message': '添加成功'})


# 获取设备
class GenreList(APIView):
    def get(self, request):
        genre = Genre.objects.all()
        genrelist = GenreSer(genre, many=True).data
        return Response({'code': 200, 'genrelist': genrelist})


# 生成随机标签名
class FixingName(APIView):
    def get(self, request):
        get_name = request.GET.get('0', None)
        # 随机生成一个EF开头的字符串
        name = 'FE' + str(int(time.time()))
        # 判断当前名字与生成的是否一致
        if name == get_name:
            # 一致：返回请求过快
            return Response({'code': 405, 'message': '请求过快'})
        return Response({'code': 200, 'message': '生成成功', 'name': name})
